package com.loong.filter;

import com.loong.pojo.User;
import com.loong.service.UserService;
import com.loong.service.impl.UserServiceImpl;
import com.loong.utils.Base64Utils;
import com.loong.utils.Constants;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/login.jsp")//默认情况下，过滤器只会过滤正常请求和重定向
public class AutoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 这里可以做一些自动登录的操作，比如从cookie中获取用户信息，然后直接登录，跳过登录页面
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();
        if (cookies!= null) {
            //本地存储了cookie
            String content = null;
            for (Cookie cookie : cookies) {
                //找到自动登录的cookie
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    content = cookie.getValue();
                    break;
                }
            }
            if (content != null) {
                //读取到了
                content = Base64Utils.decode(content);
                String[] split = content.split(Constants.FLAG);
                String username = split[0];
                String password = split[1];

                UserService userService = new UserServiceImpl();
                User user = userService.login(username, password);
                if (user != null) {
                    //登录失败，跳回登录页面
                    HttpSession session = request.getSession();
                    session.setAttribute("loginUser", user);
                    HttpServletResponse response = (HttpServletResponse) servletResponse;
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } else {
                //本地没有cookie,放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }else {
            //本地没有cookie,放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
    }
}
